import React, { Component } from "react";

import {
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Button,
  Row,
  Col,
  Pagination,
  DatePicker,
  Modal
} from "antd";
import Content from "../../components/Content/Content";
import moment from "moment";

const { Item } = Form;
const data = [];

for (let i = 0; i < 30; i++) {
  data.push({
    id: i.toString(),
    name: `Edrward ${i}`,
    age: 32,
    address: `London Park no. ${i}`
  });
}
const EditableContext = React.createContext();

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === "number") {
      return <InputNumber />;
    }
    return <Input />;
  };

  renderCell = ({ getFieldDecorator }) => {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      children,
      ...restProps
    } = this.props;
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item style={{ margin: 0, width: "100%" }}>
            {getFieldDecorator(dataIndex, {
              rules: [
                {
                  required: true,
                  message: `${title}不可为空!`
                }
              ],
              initialValue: record[dataIndex]
            })(this.getInput())}
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  render() {
    return (
      <EditableContext.Consumer>{this.renderCell}</EditableContext.Consumer>
    );
  }
}

class EditableTable extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      dataSource: data, 
      editingKey: "" ,

      selectedRowKeys: [],

      searchParams: {},
      
      count: 0,
      pageNum: 1,
      pageSize: 100
    };

    this.columns = [
      {
        title: "序号",
        dataIndex: "id",
        editable: true
      },
      {
        title: "共享单位类型",
        dataIndex: "out_gxdw",
        editable: true
      },
      {
        title: "共享单位名称",
        dataIndex: "unit_name",
        editable: true
      },
      {
        title: "共享课题组名称",
        dataIndex: "out_group",
        editable: true
      },
      {
        title: "使用人",
        dataIndex: "user_share",
        editable: true
      },
      {
        title: "使用人联系方式",
        dataIndex: "user_tel",
        editable: true
      },
      {
        title: "使用人联系邮箱",
        dataIndex: "user_email",
        editable: true
      },
      {
        title: "使用时间",
        dataIndex: "sevice_time",
        editable: true
      },
      {
        title: "是否反馈",
        dataIndex: "is_feedback",
        editable: true
      },
      {
        title: "反馈时间",
        dataIndex: "feedback_time",
        editable: true
      },
      {
        title: "使用结果",
        dataIndex: "sevice_result",
        editable: true
      },
      {
        title: "出库人",
        dataIndex: "worker",
        editable: true
      },
      {
        title: "出库时间",
        dataIndex: "delivery_time",
        editable: true
      },
      {
        title: "出库批次",
        dataIndex: "compound_ckpc",
        editable: true
      },
      {
        title: "粗提品出库数量",
        dataIndex: "compound_ctpsl",
        editable: true
      },
      {
        title: "筛选菌株编号",
        dataIndex: "sxjj_id",
        editable: true
      },
      {
        title: "预计筛选周期",
        dataIndex: "screen_cycle",
        editable: true
      },
      {
        title: "备注说明",
        dataIndex: "remark",
        editable: true
      },
      {
        title: "操作",
        dataIndex: "operation",
        fixed: "right",
        width: 200,
        render: (text, record) => {
          const { editingKey } = this.state;
          const editable = this.isEditing(record);
          return editable ? (
            <span>
              <EditableContext.Consumer>
                {form => (
                  <Button
                    type="primary"
                    onClick={() => this.save(record)}
                    style={{ marginRight: 8 }}
                  >
                    保存
                  </Button> 
                )}
              </EditableContext.Consumer>
              <Popconfirm
                title="确认取消?"
                onConfirm={() => this.cancel(record.id)}
              >
                <Button>取消</Button>
              </Popconfirm>
            </span>
          ) : (
            <Button
              type="dashed"
              disabled={editingKey !== ""}
              onClick={() => this.edit(record.id)}
            >
              编辑
            </Button>
          );
        }
      }
    ];
  }

  loadData = (current = 1) => {

    this.setState({ search_loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        search_loading: false
      });
    }, 1000);
    
    let { searchParams } = this.state;
    
    const url = global.api.crudeFeedback
    + "?q_person=" + (this.state.searchParams.q_person || "")
    + "&sevice_result=" + (this.state.searchParams.sevice_result || "")
    + "&feedback_time=" + (this.state.searchParams.feedback_time || "")
    + "&delivery_time=" + (this.state.searchParams.delivery_time || "")
    + "&is_feedback=" + (this.state.searchParams.is_feedback || "")
    + "&unit_name=" + (this.state.searchParams.unit_name || "")
    + "&compound_ctpsl=" + (this.state.searchParams.compound_ctpsl || "")
    + "&m_name=" + (this.state.searchParams.m_name || "")
    + "&compound_ckpc=" + (this.state.searchParams.compound_ckpc || "");
    
    return global.getdata.get(url, {page_index: current, page_size: this.state.pageSize, search: {}})
    .then(res => {
      this.setState({dataSource: res.results, count: res.count, newData: {}})
    })
    .catch(err => {
      Modal.error({
        content: '数据加载失败！'
      })
    }) 

  }

  componentDidMount() {
    this.loadData(1);
  }

  isEditing = record => record.id === this.state.editingKey;

  cancel = () => {
    this.setState({ editingKey: "" });
  };

  save(record) {
    const url = global.api.crudeFeedback + record + '/';
    return global.updatedata.put(url, record)
    .then(res => {  
      this.loadData(1);
      Modal.success({
        content: '更新成功!',
      });
    })
    .catch(err => {
      Modal.error({
        content: '更新出错!',
      });
    })  
  }

  edit(id) {
    this.setState({ editingKey: id });
  }

  start = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);
  };
  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  //分页器
  
  // 导出到本地
  outToLocal = () => {
    this.setState({ loading: true });
    // ajax request after empty completing
    setTimeout(() => {
      this.setState({
        selectedRowKeys: [],
        loading: false
      });
    }, 1000);

    let selectedRowKeys = this.state.selectedRowKeys;
    if(selectedRowKeys) {
      for( let x of selectedRowKeys ) {
        let record = this.state.dataSource[x];
        let id = record.id;
        // TODO 跳转到导出URL
      }
    }   

  };
  
  render() {
    const { selectedRowKeys,loading, } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      hideDefaultSelections: true,
      selections: [
        {
          key: 'odd',
          text: '选择双数',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return false;
              }
              return true;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
        {
          key: 'even',
          text: '选择单数',
          onSelect: changableRowKeys => {
            let newSelectedRowKeys = [];
            newSelectedRowKeys = changableRowKeys.filter((key, index) => {
              if (index % 2 !== 0) {
                return true;
              }
              return false;
            });
            this.setState({ selectedRowKeys: newSelectedRowKeys });
          },
        },
      ],
    };
    const components = {
      body: {
        cell: EditableCell
      }
    };

    const columns = this.columns.map(col => {
      if (!col.editable) {
        return col;
      }
      return {
        ...col,
        onCell: record => ({
          record,
          inputType: col.dataIndex === "age" ? "number" : "text",
          dataIndex: col.dataIndex,
          title: col.title,
          editing: this.isEditing(record)
        })
      };
    });

    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 }
      }
    };

    const hasSelected = selectedRowKeys.length > 0;

    return (
      <Content>
        <Form
          {...formItemLayout}
          onSubmit={this.onSubmit}
          colon={false}
          style={{ borderBottom: "20px solid #f0f2f5" }}
        >
          <div style={{ display: "flex" }}>
            <span style={{ flex: 1 }}>
              <Item label="出库批次">
                <Input onChange={e => this.state.searchParams.compound_ckpc  = e.target.value } />
              </Item>
              <Item label="粗提品数量">
                <Input onChange={e => this.state.searchParams.compound_ctpsl  = e.target.value } />
              </Item>
              <Item label="筛选方法模型">
                <Input onChange={e => this.state.searchParams.m_name  = e.target.value } />
              </Item>
              <Item label="取样时间">
                <DatePicker onChange={(value, dateString) => this.state.searchParams.delivery_time = dateString} style={{ width: "100%" }} />
              </Item>
              <Item label="取样人">
                <Input onChange={e => this.state.searchParams.q_person  = e.target.value } />
              </Item>
            </span>
            <span style={{ flex: 1 }}>
              <Item label="所属单位">
                <Input onChange={e => this.state.searchParams.unit_name  = e.target.value } />
              </Item>
              <Item label="是否反馈">
                <Input onChange={e => this.state.searchParams.is_feedback  = e.target.value } />
              </Item>
              <Item label="反馈结果">
                <Input onChange={e => this.state.searchParams.sevice_result  = e.target.value } />
              </Item>
              <Item label="反馈时间">
                <Input onChange={e => this.state.searchParams.feedback_time  = e.target.value } style={{ width: "100%" }} />
              </Item>
            </span>
          </div>

          <Item wrapperCol={{ span: 10, offset: 3 }}>
            <Row guuter={16}>
              <Col span={5}> 
                <Button type="primary" htmlType="submit" onClick={()=>this.loadData(1)} loading={this.state.loading}>
                  精确查询
                </Button>
              </Col>
              <Col span={5}>
              </Col>
            </Row>
          </Item>
        </Form>
        <Button
          type="primary"
          loading={loading}
          onClick={this.outToLocal}
          disabled={!hasSelected}
          style={{ marginLeft: 20, marginTop: 15 }}
        >
          导出
        </Button>
        <EditableContext.Provider value={this.props.form}>
          <Table
            rowSelection={rowSelection}
            components={components}
            bordered
            dataSource={this.state.dataSource}
            columns={columns}
            rowClassName="editable-row"
            pagination={false}
            scroll={{ x:4000, y: 300 }}
            
          />
            <Pagination
              showSizeChanger
              defaultCurrent={10}
              total={45}
              pageSizeOptions={['10', '20', '30', '40','50','60','70','80','90','100']	}
            />
        </EditableContext.Provider>
      </Content>
    );
  }
}

const CrudeExtractFeedback = Form.create()(EditableTable);
export default CrudeExtractFeedback;
